<?php
namespace app\admin\controller\mall;

/**
 * 商品控制器
 */

use app\common\controller\AdminController;

use think\facade\Session;
use think\facade\View;
use think\facade\Db;
use think\app;

class Item extends AdminController
{
    public function initialize()
    {
        parent::initialize();
        $this->model = app('app\common\model\mall\Item');
        $this->ItemSku = app('app\common\model\mall\ItemSku');
        $this->ItemSkuSpec = app('app\common\model\mall\ItemSkuSpec');
        $this->ItemSpec = app('app\common\model\mall\ItemSpec');
        $this->ItemSpecValue = app('app\common\model\mall\ItemSpecValue');
        $this->ItemCategory = app('app\common\model\common\Categories');
        $this->MarketItem = app('app\common\model\market\MarketItem');
    }

    /**
     * 商品审核列表
     * @return View
     */
    public function check_index()
    {
        //平台审核需获取所有商家数据，故传type值区分，屏蔽store_id判断
        $type = 1;
        View::assign('type', $type);
        return view('index');
    }


    /**
     * 审核商品
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|mixed|\think\response\Json|\think\response\View
     */
    public function check()
    {
        if ($this->request->isPost()) { //更新操作

            $data = $this->request->only(['id','comment','status']);

            $info = $this->model->find($data['id']);

            try {
                Db::startTrans();

                $goods = $info->save($data);


                Db::commit();

                return json(['code' => 1, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '更新失败' . $e->getMessage()]);


            }
        } else {//页面数据回显


            $data['id'] = $this->request->param('id');

            $info = $this->model->with(['ItemSku', 'ItemSkuSpec' => function ($query) {
                $query->with('ItemSpec')->group('spec_id')->select();
            }])->find($data['id'])->toArray();


            //分类
            $categories = $this->ItemCategory->with('allChilds')->where(['parent_id' => 0, 'type' => 3])->select();
            //sku
            $sku = $this->ItemSpec->with('spec_value')->select();
            //规格名
            if ($info['spec_type'] == 2) {
                foreach (explode('_', $info['ItemSku'][0]['spec_sku_id']) as $k => $v) {
                    $list[] = $this->ItemSpecValue->where('spec_value_id', $v)->with('category')->select()->toArray();
                }


                //sku
                //$sku = $this->ItemSpec->with('spec_value')->get();

                $spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_id');

                $spec_value = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_value_id');


                $item_spec_value = $this->ItemSpecValue->column('*', 'spec_value_id');


                //获取sku组合
                foreach ($info['ItemSku'] as $key => $value) {

                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                        $info['ItemSku'][$key]['spec'][$k] = $item_spec_value[$v]['spec_value'];
                    }
                }

                //判断是否存在规格中
                foreach ($sku as $key => $value) {

                    if (in_array($value->spec_id, $spec)) {
                        $value->active = 'sku-active';
                    } else {
                        $value->active = ' ';
                    }
                    foreach ($value->spec_value as $k => $v) {

                        if (in_array($v->spec_value_id, $spec_value)) {
                            $value->spec_value[$k]['active'] = 'sku-active';
                        } else {
                            $value->spec_value[$k]['active'] = ' ';
                        }
                    }
                }


                return view('check', compact('info', 'categories', 'sku', 'list'));

            }
            return view('check', compact('info', 'categories', 'sku'));

        }
    }

    /**
     * 模型关联
     */
    public function get_with()
    {
        return ['store'];
    }


    public function otherData()
    {
        $type = 0;
        View::assign('type', $type);
    }

    /**
     * 添加商品
     * @param ArticleRequest $this ->request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function add()
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $post = $this->request->only(['title', 'id', 'type','is_subscribe','special','is_discount','goods_no','can_refund','category_id', 'thumb', 'image', 'spec', 'content']);
                $rule = [];
                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($post ?? []);
                }

                $this->validate($post, $rule);

                $post['app_id'] = $this->model->getApp();
                $post['store_id'] = $this->model->get_store();
                //商品主表获取总库存和最低单价
                $post['inventory'] = array_sum(array_column($post['spec'], 'inventory'));
                $post['goods_price'] = min(array_column($post['spec'], 'goods_price'));
                $this->model->save($post); //商品数据入库

                $skuData = $post['spec'];//多规格数据

                foreach ($skuData as $key => $value) {
                    $skuData[$key]['goods_id'] = $this->model->id;
                    $skuData[$key]['app_id'] = $this->model->getApp();
                    //spec
                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                        $spec[$k]['goods_id'] = $this->model->id;
                        $spec[$k]['app_id'] = $this->model->getApp();
                        $spec[$k]['spec_id'] = $this->ItemSpecValue->where('spec_value_id', $v)->value('spec_id');

                        //规格名称组装
                        $skuData[$key]['spec_sku_name'][$k] = $this->ItemSpecValue->where('spec_value_id', $v)->value('spec_value');

                        $spec[$k]['spec_value_id'] = $v;
                        if ($this->ItemSkuSpec->where($spec[$k])->find()) { //去重
                            unset($spec[$k]);
                        }
                    }
                    $skuData[$key]['spec_sku_name'] = implode('/',$skuData[$key]['spec_sku_name'] );
                    $this->ItemSkuSpec->saveAll($spec);

                }
                //sku添加
                $this->ItemSku->saveAll($skuData);

                Db::commit();
                return json(['code' => 1, 'msg' => '新增成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '新增失败' . $e->getMessage()]);

            }
        } else {
            //分类
            $categories = $this->ItemCategory->with('allChilds')->where(['parent_id' => 0, 'type' => 3])->select();

            //sku
            $sku = $this->ItemSpec->with('SpecValue')->select();

            //dd($sku);
            return view('edit', compact('categories', 'sku'));
        }
    }

    /**
     * 更新商品
     * @param $data ['id']
     * @return \Illuminate\Contracts\View\View
     */
    public function edit()
    {
        if ($this->request->isPost()) { //更新操作

            $data = $this->request->only(['title', 'id', 'type', 'is_subscribe','goods_no','special','is_discount', 'can_refund','category_id', 'thumb', 'image', 'spec', 'content']);

            $info = $this->model->find($data['id']);

            try {
                Db::startTrans();

                if (method_exists($this, 'get_check_rule')) {
                    $rule = $this->get_check_rule($data ?? []);
                    $this->validate($data, $rule);
                }
                //商品主表获取总库存和最低单价
                $data['inventory'] = array_sum(array_column($data['spec'], 'inventory'));
                $data['goods_price'] = min(array_column($data['spec'], 'goods_price'));

                $data['status'] = 0; //修改之后需重新审核
                $goods = $info->save($data);


                $skuData = $data['spec'];//多规格数据

                //删除之前存在的规格数据
                //先删除不存在attr_id之中的sku
                $not_id = array_column($skuData, 'sku_id');
                if (is_null($not_id) == false) {
                    $sku_no_list = $this->ItemSku->where('goods_id', $data['id'])->whereNotIn('id', $not_id)->select();
                    $sku_no_list && $sku_no_list->delete();

                } else {
                    $sku_no_list = $this->ItemSku->where('goods_id', $data['id'])->select();
                    $sku_no_list && $sku_no_list->delete();
                }

                /*$no_spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->select();
                $no_spec && $no_spec->delete();*/

                //定义空数组装规格值
                $no_spec = [];

                foreach ($skuData as $key => $value) {
//spe
                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {
                        $spec[$k]['goods_id'] = $data['id'];

                        $spec[$k]['spec_id'] = $this->ItemSpecValue->where('spec_value_id', $v)->value('spec_id');
                        $spec[$k]['spec_value_id'] = $v;
                        array_push($no_spec, $v);
                        //规格名称组装
                        $skuData[$key]['spec_sku_name'][$k] = $this->ItemSpecValue->where('spec_value_id', $v)->value('spec_value');

                        //将所有规格值传来的组装，在与数据库判断删除之前废弃的
                        if ($this->ItemSkuSpec->where($spec[$k])->find()) { //去重
                            unset($spec[$k]);
                        }
                    }

                    $skuData[$key]['spec_sku_name'] = implode('/',$skuData[$key]['spec_sku_name'] );

                    //存在则修改，不存在就新增
                    if (isset($value['sku_id']) && $this->ItemSku->find($value['sku_id'])) {

                        $skuData[$key]['id'] = $value['sku_id'];
                        $this->ItemSku->find($value['sku_id'])->save($skuData[$key]);
                        /*$info[$key] = $this->ItemSku->find($value['sku_id']);
                        dd($info[$key]);*/
                        //$this->ItemSku->where('id',$value['sku_id'])->strict(false)->save($value);
                        //$info[$key]->save($skuData[$key]);
                    } else {
                        $this->ItemSku->save($skuData[$key]);
                        $skuData[$key]['goods_id'] = $data['id'];


                        $this->ItemSkuSpec->saveAll($spec);

                    }

                }
                $no_specs = array_unique($no_spec);

                //删除所有废弃的规格值
                $no_spec_list = $this->ItemSkuSpec->where('goods_id', $data['id'])->whereNotIn('spec_value_id', $no_specs)->select();
                $no_spec_list && $no_spec_list->delete();
                //dd($skuData);
                //$this->ItemSku->saveAll($skuData);

                Db::commit();

                return json(['code' => 1, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => '更新失败' . $e->getMessage()]);


            }
        } else {//页面数据回显


            $data['id'] = $this->request->param('id');

            $info = $this->model->with(['ItemSku', 'ItemSkuSpec' => function ($query) {
                $query->with('ItemSpec')->group('spec_id')->select();
            }])->find($data['id'])->toArray();


            //分类
            $categories = $this->ItemCategory->with('allChilds')->where(['parent_id' => 0, 'type' => 3])->select();
            //sku
            $sku = $this->ItemSpec->with('spec_value')->select();
            //规格名
            if ($info['spec_type'] == 2) {
                foreach (explode('_', $info['ItemSku'][0]['spec_sku_id']) as $k => $v) {
                    $list[] = $this->ItemSpecValue->where('spec_value_id', $v)->with('category')->select()->toArray();
                }


                //sku
                //$sku = $this->ItemSpec->with('spec_value')->get();

                $spec = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_id');

                $spec_value = $this->ItemSkuSpec->where('goods_id', $data['id'])->column('spec_value_id');


                $item_spec_value = $this->ItemSpecValue->column('*', 'spec_value_id');


                //获取sku组合
                foreach ($info['ItemSku'] as $key => $value) {

                    foreach (explode('_', $value['spec_sku_id']) as $k => $v) {

                        $info['ItemSku'][$key]['spec'][$k] = $item_spec_value[$v]['spec_value'];
                    }
                }

                //判断是否存在规格中
                foreach ($sku as $key => $value) {

                    if (in_array($value->spec_id, $spec)) {
                        $value->active = 'sku-active';
                    } else {
                        $value->active = ' ';
                    }
                    foreach ($value->spec_value as $k => $v) {

                        if (in_array($v->spec_value_id, $spec_value)) {
                            $value->spec_value[$k]['active'] = 'sku-active';
                        } else {
                            $value->spec_value[$k]['active'] = ' ';
                        }
                    }
                }


                return view('edit', compact('info', 'categories', 'sku', 'list'));

            }
            return view('edit', compact('info', 'categories', 'sku'));

        }


    }


    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy()
    {
        $ids = $this->request->param('ids');
        if (!is_array($ids) || empty($ids)) {
            return json(['code' => 1, 'msg' => '请选择删除项']);
        }

        try {
            $items = $this->model->destroy($ids);
            $skus = $this->ItemSku->whereIn('goods_id', $ids)->select();
            $skus->delete();
            $sku_spec = $this->ItemSkuSpec->whereIn('goods_id', $ids)->select();
            $sku_spec->delete();
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
    }

    /**
     * 单个字段操作
     * @return \think\response\Json
     */
    public function action()
    {

        $param = $this->request->param();

        try {
            $row = $this->model->where('id', $param['id'])->find();

            $row->save($param);

        } catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage()]);
        }
        return json(['code' => 0, 'msg' => '操作成功']);
    }


    /**
     * 条件查询
     * @param array $arr
     * @return array
     */
    public function get_where($arr = [])
    {
        $array = [];
        if (@$arr['market_type'] == 1) { //判断是否营销活动选择商品
            $item_ids = $this->MarketItem->column('item_id');
            $array[] = ['status', '=', 1];
            $array[] = ['id', 'not in', implode(',', $item_ids)];
        }
        $admin = Session::get('admin');
        @$arr['type'] != 1 && $array[] = ['store_id', '=', $admin['store_id']];
        if (isset($arr['goods_name']) && !empty($arr['goods_name'])) {
            $array[] = ['goods_name', 'like', '%' . $arr['goods_name'] . '%'];
        }

        isset($arr['goods_no']) && !empty($arr['goods_no']) && $array[] = ['goods_no', '=', $arr['goods_no']];
        isset($arr['status']) && !empty($arr['status']) && $array[] = ['status', '=', $arr['status']];


        return $array;
    }
}